<template>
  <el-table :data="state.dataSource">

    <el-table-column prop="id" width="55" label="id" />

    <el-table-column prop="originFileName" label="原文件名" />
    <el-table-column prop="object" label="object" />
    <el-table-column prop="size" label="文件大小">
      <template #default="scope">
        {{ convertFileSizeUnit(scope.row.size) }}
      </template>
    </el-table-column>
    <el-table-column prop="progress" label="下载进度">
      <template #default="scope">
        <el-progress v-if="scope.row.progress" :percentage="scope.row.progress / 100" />
      </template>
    </el-table-column>
    <el-table-column prop="progress" label="下载进度">
      <!-- 操作 -->
      <template #default="scope">
        <template v-if="scope.row.status === undefined || scope.row.status === 'error'">
          <el-button type="primary" @click="downloadFile(scope.row)">
            <template #icon><icon-download /></template>
          </el-button>
        </template>
        <template v-else>
          <!-- 暂停 -->
          <el-button v-if="scope.row.status === 'downloading'" type="primary" @click="puaseDownload(record)">
            <template #icon><icon-pause-circle /></template>
          </el-button>
          <!-- 继续下载 -->
          <el-button v-else type="primary" @click="downloadFile(scope.row)">
            <template #icon><icon-play-circle /></template>
          </el-button>
        </template>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import { reactive, onMounted } from 'vue'
// import type { TableColumnData } from '@arco-design/web-vue-legacy'
import { CHUNK_SIZE } from '@/utils/fileUtil.js'
import { convertFileSizeUnit, downloadFileByBlob } from '@/utils/fileUtil.js'
// import { chunkDownloadFile, fetchFileList } from '../services/apis'
import { chunkDownloadFile, fetchFileList } from '@/api/upload'

export default {
  name: 'FileTable',
  components: {
  },
  data() {
    return {
      downloadStatus: {
        progress: 0, // 进度
        status: 'downloading', // 状态 'downloading' | 'pause' | 'error'
      },
      state: {
        dataSource: [],
        blobRef: [],
      },
      columns: [
        { title: '主键id', dataIndex: 'id', width: 80 },
        { title: '原文件名', dataIndex: 'originFileName', ellipsis: true, tooltip: true },
        { title: 'object', dataIndex: 'object', ellipsis: true, tooltip: true },
        { title: '文件大小', dataIndex: 'size', slotName: 'size', width: 120 },
        { title: '下载进度', dataIndex: 'progress', slotName: 'progress' },
        { title: '操作', dataIndex: 'status', slotName: 'status', width: 120 }
      ],
      CHUNK_SIZE: 1024 * 1024 * 5
    }
  },
  methods: {
    downloadFile(record) {
      const index = this.state.dataSource.findIndex((item) => item.id === record.id)
      this.state.dataSource[index].status = 'downloading'

      const totalChunks = Math.ceil(record.size / CHUNK_SIZE) // 请求次数，可自定义调整分片大小，这里默认了上传分片大小
      // 如果是暂停，根据已下载的，找到断点，偏移长度进行下载
      const offset = this.state.blobRef.get(record.id)?.length || 0

      for (let i = offset + 1; i <= totalChunks; i++) {
        // 暂停/错误 终止后续请求
        if (this.state.dataSource[index].status !== 'downloading') return

        const start = CHUNK_SIZE * (i - 1)
        let end = CHUNK_SIZE * i - 1
        if (end > record.size) end = record.size // 虽然超出不会影响内容读取，但是会影响进度条的展示
        chunkDownloadFile(record.id, `bytes=${start}-${end}`).then(res => {
          if (res.data.code === 200) {
            const currentDataBlob = this.state.blobRef.get(record.id) || []
            // 记录当前数据的分片 blob
            this.state.blobRef.set(record.id, [...currentDataBlob, res])
            this.state.dataSource[index].progress = Math.floor((end / record.size) * 100)
          } else {
            this.state.dataSource[index].status = 'error'
          }
        })
      }
      this.state.dataSource[index].status = undefined // 重置状态
      this.state.dataSource[index].progress = undefined // 重置进度条
      const blob = new Blob(this.state.blobRef.get(record.id))
      downloadFileByBlob(blob, record.originFileName)
    },
    //暂停
    puaseDownload(record) {
      record.status = 'pause'
    },
    /**
     * 根据文件流转成的 blob 下载文件
     * @param blob 文件 blob
     * @param filename 文件名
     */
    downloadFileByBlob(blob, filename) {
      const href = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = href
      a.download = filename
      a.rel = 'noopener noreferrer'
      document.body.append(a)
      a.click()
      URL.revokeObjectURL(href) //释放URL对象
      a.remove()
    }
  },
  mounted() {
    //const { code, data } = await fetchFileList()
    fetchFileList().then(res => {
      if (res.data.code === 200) {
        this.state.dataSource = res.data
      }
    })
  }
}
</script>

<style></style>
